<!--
* description: 车身颜色
* author: ligy
* createdDate: 2020-12-4
-->
<template>
  <div class="app-container app-container-table">
    <!-- 单表格模版页面 -->
    <one-table-template
      ref="multipleTable"
      :dynamic-api-config="dynamicApiConfig"
      :dynamic-buttons="dynamicButtons"
      :dynamic-components="tableComponents"
      :dynamic-table-cols="dynamicTableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-more-btn="false"
      :dynamic-is-show-select="false"
      :refresh-table-key="refreshTableKey"
      :callback-obj="callbackObj"
      @hiddenColData="hiddenColData"
    />
    <Edit
      v-if="dialogShow"
      :is-dialog-visible="dialogShow"
      :data-for-form="editRowData"
      :title-name="titleName"
      @closeEdit="closeEdit"
      @save="save"
    />
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import api from '@/api/vehicleManagement'
import { exportExcel } from '@/utils/getTimeString'
import OneTableTemplate from '@/components/templates/oneTable'
import Edit from './edit'
import Vue from 'vue'

export default {
  name: 'VeTotalInfor',
  components: {
    OneTableTemplate,
    Edit
  },
  mixins: [oneTableWithViewTemplateMixins],
  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData(
      // 同时加载当前页面和编辑框页面的配置
      [to.path, ''],
      function() {
        next()
      }
    )
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      titleName: '车身颜色维护',
      refreshTableKey: '0',
      dialogShow: false,
      editPopupsState: 'add',
      editRowData: {},
      // table表格查询API配置对象
      dynamicApiConfig: api.veBodyColor,
      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '颜色编码：',
              codeField: 'carColorCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: '颜色名称：',
              codeField: 'carColorName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '状态：',
              codeField: 'isEnableCode',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'AsId,AsText',
              options: [
                { AsId: '1', AsText: '启用' },
                { AsId: '0', AsText: '停用' }
              ],
              type: 'inputText',
              isMust: true
            }
          ],
      // form 的表单对象
      formField: this.$utils.getFormField(
        this,
        {
          carColorCode: '',
          carColorName: '',
          isEnableCode: '1'
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      ),
      // 动态组件-按钮
      dynamicButtons:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
          : [
            {
              compKey: 'btnKey0',
              type: '',
              size: 'small',
              name: 'export',
              position: 'left',
              clickEvent: () => this.exportExcelAll(),
              text: this.$t('sys.button.export')// 导出
            },
            {
              compKey: 'btnKey1',
              type: 'primary',
              size: 'small',
              name: 'search',
              clickEvent: () => this.queryTable(1),
              text: '查询'
            },
            {
              compKey: 'btnKey2',
              type: '',
              size: 'small',
              name: 'reset',
              clickEvent: () => this.reset(),
              text: '重置'
            }
          ],
      // 动态组件-表格网格列
      dynamicTableCols:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols.length >
          0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols
          : [
            {
              label: '操作',
              minWidth: 180,
              fixed: true,
              isComponent: true,
              comps: [
                {
                  compKey: 'propKey1',
                  labelName: '编辑',
                  component: () => import('@/components/org/linkButton'),
                  clickEvent: (index) => this.edit(index)
                }
              ]
            },
            {
              prop: 'carColorId',
              label: '主键ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'carColorCode',
              label: '车身颜色编码'
            },
            {
              prop: 'carColorName',
              label: '车身颜色名称',
              align: 'center'
            },
            {
              prop: 'carColorPrice',
              label: '价格'
            },
            {
              prop: 'isEnableCode',
              label: '状态'
            }
          ],
      // 单表格模版页面组件回调事件
      callbackObj: {
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.handleSelectionChange(selection)
        }
      }
    }
  },
  mounted() {
    // 列表查询
    const that = this
    setTimeout(function() {
      that.queryTable(1)
    }, 1000)
  },
  methods: {
    // 当选择项发生变化时会触发该事件
    handleSelectionChange(selection) {
      const btns = this.dynamicButtons.filter((o) => o.disabled !== undefined)
      if (btns.length > 0) {
        const isCheck = selection && selection.length > 0
        btns.forEach((item) => {
          item.disabled = !isCheck
        })
      }
    },

    hiddenColData(data) {
      if (data && data.length > 0) {
        this.refreshTableKey += 1
        this.dynamicTableCols = data
      }
    },

    // 新增--编辑
    edit(index) {
      this.dialogShow = true
      this.editRowData = this.$refs['multipleTable'].list[index]
    },

    // 关闭编辑页面
    closeEdit(type) {
      this.dialogShow = false
      // 新增或编辑成功后操作
      if (type === 1) {
        // 调查询接口
        this.queryTable(1)
      }
    },

    // 删除按钮单条删除
    delOneData(row) {
      const data = [this.$refs['multipleTable'].list[row]]
      this.delData(data)
    },

    // 数据批量删除
    delSeleteData() {
      const data = this.$refs['multipleTable'].$refs['multipleTable'].selection
      this.delData(data)
    },

    // 删除
    delData(selectData) {
      //   const that = this
      //   this.$confirm('确定要删除吗', '提示', {
      //     confirmButtonText: '确认',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   }).then(() => {
      //     const saveObjList = []
      //     selectData.forEach((item) => {
      //       saveObjList.push(item.id)
      //     })
      //     const saveObj = {
      //       id: saveObjList.join()
      //     }
      //     that.$utils.apiRrequest(that, 'mutation', testApis.dbSenceApiMutationBatchDelObject, saveObj, (data) => {
      //       if (data) {
      //         that.$message({
      //           message: '删除成功',
      //           type: 'success',
      //           duration: 2000
      //         })
      //         that.queryTable(1)
      //       }
      //     })
      //   }).catch(() => {})
    },
    save(val) {
      this.listLoading = true
      console.log(val)
      const returnObj = {
      // api配置
        ServiceCode: 'updateVehicleColor',
        apiUrl: '/mp/e3sh/vesale/basics/vehicleColourService/updateVehicleColor.do',
        variables: val
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(returnObj, null, this.dynamicApiStyle)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD, this.dynamicApiStyle).then(response => {
        if (response.result === '0') {
          this.listLoading = false
          if (response.msg) {
            this.$message({
              message: response.msg,
              type: 'warn',
              uration: 2000
            })
          }
          return
        }
        this.listLoading = false
        // 返回json
        if (response.msg) {
          this.$message({
            message: response.msg,
            type: 'warn',
            uration: 2000
          })
        }
        this.closeEdit(1)
        this.listLoading = false
      }).catch(err => {
        console.info(err)
        this.listLoading = false
      })
    },
    exportExcelAll() {
      exportExcel(this.formField, '/mp/e3sh/vesale/basics/vehicleColourService/exportVehicleColor.do', 'exportVehicleColor', '车身颜色维护')
    }
  }
}
</script>
